exports.find = function ({query, user_id}, {models: {UsersAccounts}, controller}) {
    query.user_id = user_id;
    return UsersAccounts.findAll(controller.pagination({
        params: query,
        filters: ['domain', 'username', 'status', 'user_id'],
        likes: ['nickname', 'username']
    }));
}

exports.save = function ({body, user_id}, {models: {UsersAccounts, UsersAccountsLogs}}) {
    body.user_id = user_id;
    let {domain, username} = body;
    return UsersAccounts.findOne({
        where: {
            user_id: user_id,
            domain: domain,
            username: username
        }
    }).then(function (account) {
        if (account) {
            return UsersAccounts.update(body, {where: {id: account.id}}).then(function (result) {
                let log = {
                    opt: 'update',
                    domain: domain,
                    username: username,
                    user_id: user_id,
                    ext_data: JSON.stringify(body)
                }
                if (result[0]) {
                    log.is_success = 1;
                } else {
                    log.is_success = 0;
                }
                UsersAccountsLogs.create(log);
                return {success: log.is_success};
            });
        }
        return UsersAccounts.create(body).then(function (account) {
            UsersAccountsLogs.create({
                opt: 'create',
                is_success: 1,
                domain: domain,
                username: username,
                user_id: user_id,
                ext_data: JSON.stringify(body)
            });
            return {success: true, data: account};
        });
    });
}

exports.failed = function ({body, user_id}, {models: {UsersAccountsLogs}}) {
    body.user_id = user_id;
    body.is_success = 0;
    return UsersAccountsLogs.create(body).then(function () {
        return {success: true};
    });
}